package com.zzyl.service.impl;

import com.google.common.collect.Lists;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.DeptDto;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeptMapper;
import com.zzyl.service.DeptService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.DeptVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Override
    public List<DeptVo> deptList(DeptDto deptDto) {
        return null;
    }

    @Override
    public List<DeptVo> findDeptList(DeptDto deptDto) {
        return deptMapper.selectList(deptDto);
    }

    @Override
    public TreeVo deptTreevo() {
        //获取根节点树形
        String parentDeptNo = SuperConstant.ROOT_DEPT_PARENT_ID;

        //构建查询条件
        DeptDto param = DeptDto.builder()
                .dataState(SuperConstant.DATA_STATE_0)
                .parentDeptNo(NoProcessing.processString(parentDeptNo))
                .build();
        //查询部门列表数据
        List<DeptVo> deptList =  deptMapper.selectList(param);

        if(EmptyUtil.isNullOrEmpty(deptList)){
            throw new BaseException("部门数据没有定义");
        }

        //找根节点
        DeptVo rootDept = deptList.stream().filter(d -> SuperConstant.ROOT_DEPT_PARENT_ID.equals(d.getParentDeptNo())).collect(Collectors.toList()).get(0);

        //返回的部门数据
        List<TreeItemVo> treeItemVoList = new ArrayList<>();

        //递归调用
        recursionTreeItem(treeItemVoList,rootDept,deptList);

        return TreeVo.builder().items(treeItemVoList).build();
    }

    /**
     * 递归调用拼装数据
     * @param treeItemVoList  封装返回的数据
     * @param rootDept  当前部门
     * @param deptList  部门列表（全部数据）
     */
    private void recursionTreeItem(List<TreeItemVo> treeItemVoList, DeptVo rootDept, List<DeptVo> deptList) {
        //构建item对象
        TreeItemVo treeItemVo = TreeItemVo.builder().id(rootDept.getDeptNo()).label(rootDept.getDeptName()).build();
        //获得当前部门下的子部门
        List<DeptVo> childrenDept = deptList.stream()
                .filter(n -> n.getParentDeptNo().equals(rootDept.getDeptNo()))
                .collect(Collectors.toList());
        //如果子部门不为空，则继续递归调用
        if(!EmptyUtil.isNullOrEmpty(childrenDept)){

            ArrayList<TreeItemVo> listChildren = Lists.newArrayList();
            //子部门列表
            childrenDept.forEach(dept -> {
                this.recursionTreeItem(listChildren,dept,deptList);
            });
            treeItemVo.setChildren(listChildren);
        }

        treeItemVoList.add(treeItemVo);
    }
}
